package xFGE.xDisplay.xUI
{
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.text.TextField;

	public class xButton extends MovieClip
	{
		private var _hasSelected:Boolean;
		
		private var _title:TextField;
		
		private var _touchFace:MovieClip;
		
		private var _clickEnabled:Boolean = false;   
		
		public function xButton()
		{
			//TODO: implement function
			super();
			Init();
		}
		
		public function Init():void
		{
			stop();
			buttonMode = true;
			_title = getChildByName("__title") as TextField;
			_touchFace = getChildByName("__touchFace") as MovieClip;
			if(_touchFace==null) throw(new Error("xButtonMC没有__touchFace"));
			/* if(_title == null){
				_title = new TextField();
//				addChild(_title);
			}  */
			if(_title){
				_title.mouseEnabled = false;
				_title.selectable = false;
			}
			_touchFace.alpha = 0;
			_touchFace.addEventListener(MouseEvent.ROLL_OUT,_onRollOut);
			_touchFace.addEventListener(MouseEvent.ROLL_OVER,_onRollOver);
			_touchFace.addEventListener(MouseEvent.MOUSE_DOWN,_onMouseDown);
			_touchFace.addEventListener(MouseEvent.MOUSE_UP,_onMouseUp);
			_touchFace.addEventListener(MouseEvent.CLICK,_onClick);
		}
		
		public function SetSelected(flag:Boolean):void
		{
			if(_hasSelected==flag) return;
			_hasSelected = flag;
			if(flag){
				gotoAndPlay("selected");
			}else{
				gotoAndPlay("up");
			}
		}

		public function SetTitle(title:String, color:int =-1): void
		{
			_title.text = title;
			if(color != -1){
				_title.textColor = color;
			}
		}
		
		public function SetDisable(flag:Boolean):void
		{
			mouseEnabled = !flag;
			_touchFace.mouseEnabled = !flag;
			if(!mouseEnabled) gotoAndPlay("disabled");
			else gotoAndPlay("up");
		}
		
		public function GetTile():String
		{
			return _title.text;
		}
		public function SetClickEnabled(flag:Boolean):void
		{
			_clickEnabled = flag;
		}
		
		public function hasSelected():Boolean
		{
			return _hasSelected;
		}
		private function _onRollOver(eve:MouseEvent):void
		{
			if(_hasSelected) return;
			gotoAndPlay("over");
			return;
		}
		
		private function _onRollOut(eve:MouseEvent):void
		{
			if(_hasSelected) return;
			gotoAndPlay("up");
			return;
		}
		
		private function _onMouseDown(eve:MouseEvent):void
		{
			if(_hasSelected)return;
			gotoAndPlay("down");

			return;
		}
		
		private function _onMouseUp(eve:MouseEvent):void
		{
			if(_hasSelected ) return;
			if(this.getRect(stage).contains(eve.stageX,eve.stageY)) gotoAndPlay("over");
			else gotoAndPlay("up");
			return;
		}
		
		private function _onClick(eve:MouseEvent):void
		{
			if(!_clickEnabled) return;
			if(_hasSelected == false){
				gotoAndPlay("selected");
			}else{
				_hasSelected = false;
				gotoAndPlay("over");
			}
		}
		
	}
}